/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.GenericFilterBean;

import com.rrx360.common.web.matcher.ServletPathMatcher;
import com.rrx360.common.web.util.HsrUtil;

public class ChannelFilter extends GenericFilterBean {

  private ServletPathMatcher httpsOnlyMatcher;

  private int httpPort = 80;

  private int httpsPort = 443;

  private boolean filter = true;

  public ServletPathMatcher getHttpsOnlyMatcher() {
    return httpsOnlyMatcher;
  }

  public void setHttpsOnlyMatcher(ServletPathMatcher httpsOnlyMatcher) {
    this.httpsOnlyMatcher = httpsOnlyMatcher;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest hsr = (HttpServletRequest) request;
    if (filter && httpsOnlyMatcher != null && httpsOnlyMatcher.match(hsr)) {
      if (!"https".equals(HsrUtil.getSchema(hsr))) {
        if ("GET".equals(hsr.getMethod())) {
          String queryString = hsr.getQueryString();
          String redirectUrl =
              HsrUtil.getRequestUri(hsr) + ((queryString == null) ? "" : ("?" + queryString));
          String port = httpsPort == 443 ? "" : ":" + httpsPort;
          redirectUrl = "https://" + HsrUtil.getServerName(hsr) + port + redirectUrl;
          //avoid response splitting
          redirectUrl = redirectUrl.replace("\n", " ").replace("\r", " ");
          ((HttpServletResponse) response).sendRedirect(redirectUrl);
          return;
        } else {
          ((HttpServletResponse) response).setStatus(405);
          return;
        }
      }
    }
    chain.doFilter(request, response);
  }

  public int getHttpPort() {
    return httpPort;
  }

  public void setHttpPort(int httpPort) {
    this.httpPort = httpPort;
  }

  public int getHttpsPort() {
    return httpsPort;
  }

  public void setHttpsPort(int httpsPort) {
    this.httpsPort = httpsPort;
  }

  public boolean isFilter() {
    return filter;
  }

  public void setFilter(boolean filter) {
    this.filter = filter;
  }



}
